package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;

import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
//import com.heima.utils.common.WmThreadLocalUtil;
//import com.heima.wemedia.mapper.WmNewsMapper;
//import com.heima.wemedia.mapper.WmNewsMaterialMapper;
//>>>>>>> 17d020b272b9b8d80ac044d6b4a511f9af9a69c0
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired

    private WmNewsMapper wmNewsMapper;


    @Autowired
    private WmMaterialService wmMaterialService;
    @Resource
    private WmNewsMaterialMapper newsMaterialMapper;
    @Autowired
    private AutoScanService autoScanService;
    @Autowired
    private WmTaskService taskService;

    @Override
    public ResponseResult list(WmNewsPageReqDto reqDto) {
        //参数校验
        reqDto.checkParam();

        IPage page = new Page(reqDto.getPage(), reqDto.getSize());
        //构造查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.get().getId());
        queryWrapper.eq(reqDto.getStatus() != null, WmNews::getStatus,reqDto.getStatus());

        queryWrapper.eq(reqDto.getChannelId() != null, WmNews::getChannelId,reqDto.getChannelId());
        queryWrapper.like(!StringUtils.isEmpty(reqDto.getKeyword()),WmNews::getTitle,reqDto.getKeyword());

        if(reqDto.getBeginPubDate() != null && reqDto.getEndPubDate() != null){
            queryWrapper.between(WmNews::getCreatedTime,reqDto.getBeginPubDate(),reqDto.getEndPubDate());
        }
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page,queryWrapper);

        ResponseResult result = new PageResponseResult(reqDto.getPage(),reqDto.getSize(),(int)page.getTotal());

        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //参数校验
        checkParam(wmNewsDto);
        //修改或者保存
        WmNews wmNews = saveOrUpdate(wmNewsDto);
        if(wmNews.getStatus() == WmNews.Status.NORMAL.getCode()){
            return ResponseResult.okResult(null);
        }
        //获取正文中所有的图片
        List<String> pics = getPictures(wmNewsDto.getContent());
        saveRelations(pics, wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);

        saveRelationsByCover(pics,wmNewsDto,wmNews);
//        if(wmNews.getPublishTime() != null){
//            taskService.addTask(wmNews);
//        }else{
            autoScanService.scan(wmNews.getId());
//        }

        return ResponseResult.okResult(null);
    }



    @Override
    public ResponseResult listVo(NewsAuthDto dto) {
        //参数校验
        dto.checkParam();

        IPage page = new Page(dto.getPage(), dto.getSize());
        //构造查询参数
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper();

        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        queryWrapper.like(dto.getTitle()!=null,WmNews::getTitle,dto.getTitle());

        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page,queryWrapper);

        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());

        result.setData(page.getRecords());
        return result;



    }
    //审核失败
    @Override
    public ResponseResult fail(NewsAuthDto dto) {
        //检验参数
        dto.checkParam();
        //
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus((short)2);
        wmNews.setReason(dto.getMsg());
        updateById(wmNews);
        return ResponseResult.okResult("ok");
    }
    @Autowired
    private WmUserMapper userMapper;
    @Autowired
    private WmChannelMapper channelMapper;
    @Autowired
    private IArticleClient articleClient;
    @Override
    public ResponseResult pass(NewsAuthDto dto) {
        //检验参数
        dto.checkParam();
        WmNews wmNews = getById(dto.getId());
        wmNews.setStatus((short)9);
        wmNews.setReason("发布成功");
        updateById(wmNews);

        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setAuthorId(wmNews.getUserId());
        articleDto.setId(null);
        WmUser user = userMapper.selectById(wmNews.getUserId());
        articleDto.setAuthorName(user == null ? "" : user.getName());
        //布局
        articleDto.setLayout(wmNews.getType());

        WmChannel wmChannel = channelMapper.selectById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel == null ? "" : wmChannel.getName());
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        articleClient.saveArticle(articleDto);
                return ResponseResult.okResult(null);
    }


    /**
     *
     * 封面和素材的关系
     * @param pics
     * @param newsDto
     * @param wmNews
     */
    private void saveRelationsByCover(List<String> pics,WmNewsDto newsDto,WmNews wmNews){
        List<String> images = newsDto.getImages();
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(newsDto.getType())){
            int size = pics.size();
            if(size >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = pics.stream().limit(3).collect(Collectors.toList());
            }else if(size >= 1 && size < 3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = pics.stream().limit(1).collect(Collectors.toList());
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if(!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.collectionToCommaDelimitedString(images));
            }
            updateById(wmNews);
        }

        if(!CollectionUtils.isEmpty(images)){
            saveRelations(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    /**
     * 保存素材和文章的关系
     *
     * @param pics
     * @param newsId
     */
    private void saveRelations(List<String> pics,Integer newsId,Short type){
        if(CollectionUtils.isEmpty(pics)){
            return;
        }
        List<WmMaterial> list = wmMaterialService.list(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, pics));
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        List<Integer> ids = list.stream().map(WmMaterial::getId).collect(Collectors.toList());
        newsMaterialMapper.saveRelations(ids,newsId,type);
    }


    /**
     * 从正文中获取图片素材
     *
     * @param content
     * @return
     */
    private List<String> getPictures(String content){
        List<String> pics = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content,Map.class);
        for(Map map : mapList){
            if("image".equals(map.get("type"))){
                pics.add((String)map.get("value"));
            }
        }
        return pics;
    }


    /**
     * 保存或者修改文章
     *
     * @param wmNewsDto
     * @return
     */
    private WmNews saveOrUpdate(WmNewsDto wmNewsDto){
        WmNews news = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,news);
        news.setUserId(WmThreadLocalUtil.get().getId());
        //封面图片转换aaa.jpg,bb.jpg
        if(!CollectionUtils.isEmpty(wmNewsDto.getImages())){
            news.setImages(StringUtils.collectionToCommaDelimitedString(wmNewsDto.getImages()));
        }
        news.setCreatedTime(new Date());
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNewsDto.getType())){
            news.setType(null);
        }
        if(wmNewsDto.getId() == null){
            save(news);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNewsDto.getId()));
            updateById(news);
        }

        return news;
    }

    /**
     * 参数校验
     * @param newsDto
     */
    private void checkParam(WmNewsDto newsDto){
        if(StringUtils.isEmpty(newsDto.getTitle())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(StringUtils.isEmpty(newsDto.getContent())){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
